package com.ruoyi.framework.websocket;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class MyWebSocketHandler extends TextWebSocketHandler {
    // 连接开启
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String token = session.getAttributes().get("token").toString();
        WebSocketUsers.put(token, session);
        log.info("连接开启 - {}", token);

        Map<String, Object> msg = new HashMap<>();
        msg.put("avatar", "https://q.qlogo.cn/g?b=qq&nk=1553592282&s=160");
        msg.put("info", "Lyb刘同学" + "【" + DateUtil.formatTime(new Date()) + "】");
        msg.put("text", "欢迎体验，当前在线人数：" + WebSocketUsers.getUsers().size() + "人。");
        msg.put("type", "left");
        WebSocketUsers.sendMessageToUserByText(session, JSON.toJSONString(msg));
    }

    // 连接关闭
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("连接关闭 - {}", session);
        // 移除用户
        String token = session.getAttributes().get("token").toString();
        WebSocketUsers.remove(token);
    }

    // 连接错误
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.info("连接错误 - {}", exception.getMessage());
        if (session.isOpen()) {
            session.close();
        }
        // 移出用户
        String token = session.getAttributes().get("token").toString();
        WebSocketUsers.remove(token);
    }

    // 收到消息
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
        String token = session.getAttributes().get("token").toString();
        SaSession saSession = StpUtil.getSessionByLoginId(StpUtil.getLoginIdByToken(token));
        LoginUser loginUser = (LoginUser) saSession.getTokenSign(token).getTag();

        Map<String, Object> msg = new HashMap<>();
        msg.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/160/h/160");
        msg.put("info", loginUser.getIpaddr() + "【" + DateUtil.formatTime(new Date()) + "】");
        msg.put("text", message.getPayload());
        msg.put("type", "left");
        WebSocketUsers.sendMsgToUsersExcludeMeByText(token, JSON.toJSONString(msg));

        msg.put("info", "【" + DateUtil.formatTime(new Date()) + "】" + loginUser.getIpaddr());
        msg.put("type", "right");
        WebSocketUsers.sendMessageToUserByText(session, JSON.toJSONString(msg));
    }
}
